package com.wanma.recuit.filter;

import com.wanma.recuit.pojo.User;
import com.wanma.recuit.service.LoginRegistService;
import com.wanma.recuit.util.CookiesUtils;
import com.wanma.recuit.util.EncryptUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter({"/service/*"})
public class UserAutoLoginFilter implements Filter {

//    //在Filter中注入service
//    private static ApplicationContext ctx = new ClassPathXmlApplicationContext();
//    //获取Service
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//    }
//LoginRegistService loginRegistService= (LoginRegistService) ctx.getBean("userService");
//   private LoginRegistService loginRegistService;
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
//        loginRegistService = ctx.getBean(LoginRegistService.class);
//    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        //看看用户是否当前在登录
        User userzaixian = (User)session.getAttribute("user");
        if(userzaixian==null){
            //从cookie中取，看看有没有用户的信息
            String phone = CookiesUtils.read("phone",request);
            if(phone!=null){
                String pass = CookiesUtils.read("pass",request);
                User user = new User();
                user.setPhone(EncryptUtils.decrypt(phone));
                user.setPass(pass);
                ApplicationContext applicationContext =  WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
                LoginRegistService loginRegistService = applicationContext.getBean("loginRegistServiceImpl",LoginRegistService.class);
                user = loginRegistService.loginUser(user);
                if(user!=null){
                    session.setAttribute("user",user);
                    //重新再cookie中写入用户，延续时间
                    CookiesUtils.write("phone", EncryptUtils.encrypt(user.getPhone()),"/",60*60*24*30,response);
                    CookiesUtils.write("pass", user.getPass(),"/",60*60*24*30,response);
                }
            }
        }
        chain.doFilter(req, resp);
    }

}
